package com.hulk.dryad.manage.limiter.aop;


import com.hulk.dryad.common.annotation.Limiter;
import com.hulk.dryad.common.constant.enums.BEC;
import com.hulk.dryad.manage.limiter.constant.LimiterInfo;
import com.hulk.dryad.manage.limiter.exception.LimiterException;
import com.hulk.dryad.manage.limiter.strategy.LimiterStrategy;
import com.hulk.dryad.manage.limiter.expression.LimiterInfoResolver;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;


/**
 * @author hulk
 */
@Slf4j
@Aspect
@AllArgsConstructor
public class LimiterAspect {


    private final LimiterInfoResolver limiterInfoResolver;

    private final LimiterStrategy redisLimiterStrategy;

    @Before(value = "@annotation(limiter)")
    @SneakyThrows
    public void joinPoint(JoinPoint joinPoint, Limiter limiter)  {

        LimiterInfo info = limiterInfoResolver.get(joinPoint,limiter);
        boolean b =  redisLimiterStrategy.execute(info);

        if(!b){
			String msg = info.getLimitName() + ":请求频率过高，每秒内不能超过,"+ info.getReplenish() + "笔请求。最多，"+ info.getCapacity()+ "笔请求。";
			log.warn(msg);
            throw new LimiterException(BEC.E_2021.getErrCode(),msg);
        }
        return;
    }



}